import { defineStore } from 'pinia'
import {
  getNoteList,
  getNoteDetail,
  createNote,
  updateNote,
  deleteNote,
  uploadAttachment,
  removeAttachment,
  shareNote,
  unshareNote,
  getShareableUsers,
  getShareableDepartments,
} from '@/services/disk'

// 定义笔记文档接口（适配article表结构）
interface NoteDocument {
  id: number
  name: string // 对应article表的name字段（标题）
  content: string
  create_time: string
  update_time: string
  admin_id: number // 对应article表的admin_id字段（作者）
  admin_name?: string // 作者名称
  author?: string // 创建者名称
  created_by?: number // 创建者ID
  created_by_name?: string // 创建者名称
  status?: number // 对应article_access表的status字段（替代is_shared）
  is_shared?: boolean // 是否已分享
  shared_users: Array<{ id: number; name: string }>
  shared_departments: Array<{ id: number; name: string }>
  file_ids?: string // 文件ID列表，逗号分隔的字符串
  attachments: Array<{
    id: number
    name: string
    size: number
    path: string
    ext: string
    upload_time: string
  }>
  // 声明getter/setter签名以保持兼容性
  get title(): string
  set title(val: string)
}

// 定义状态接口
interface DiskState {
  notes: NoteDocument[]
  noteTotal: number
  currentNote: NoteDocument | null
  loading: boolean
  shareableUsers: Array<{ id: number; name: string }>
  shareableDepartments: Array<{ id: number; name: string }>
}

// 分享配置接口
interface ShareConfig {
  user_ids?: string
  department_ids?: string
}

export const useDiskStore = defineStore('disk', {
  state: (): DiskState => ({
    notes: [],
    noteTotal: 0,
    currentNote: null,
    loading: false,
    shareableUsers: [],
    shareableDepartments: [],
  }),

  actions: {
    // 获取笔记列表
    async fetchNotes(params?: any) {
      try {
        this.loading = true
        const response = await getNoteList(params)
        if (response.code === 0) {
          // 正确从response.data.list获取笔记列表数组
          this.notes = response.data?.list || []
          // 使用response.data.total获取总数
          this.noteTotal = response.data?.total || 0
        }
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取笔记详情
    async fetchNoteDetail(id: number) {
      try {
        this.loading = true
        const response = await getNoteDetail(Number(id))
        if (response.code === 0) {
          this.currentNote = response.data
        }
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建笔记（适配article表的字段映射）
    async createNewNote(data: { title: string; content?: string; file_ids?: string | number[] }) {
      try {
        // 记录接收到的原始数据
        // 确保file_ids数组转换为逗号分隔的字符串格式
        const postData = {
          ...data,
          // 将file_ids数组转换为字符串，如果数组为空则传递空字符串
          file_ids: Array.isArray(data.file_ids) ? data.file_ids.join(',') : data.file_ids || '',
        }
        const response = await createNote(postData)
        // 创建成功后刷新笔记列表
        await this.fetchNotes()
        return response
      } catch (error) {
        throw error
      }
    },

    // 更新笔记（适配article表的字段映射）
    async updateExistingNote(data: {
      id: number
      title: string
      content: string
      file_ids?: string | number[]
    }) {
      try {
        // 确保file_ids数组转换为逗号分隔的字符串格式
        const postData = {
          ...data,
          // 将file_ids数组转换为字符串，如果数组为空或undefined则传递空字符串
          file_ids: Array.isArray(data.file_ids) ? data.file_ids.join(',') : data.file_ids || '',
        }
        const response = await updateNote(postData)
        // 更新当前笔记和列表中的对应笔记
        if (this.currentNote && this.currentNote.id === data.id) {
          this.currentNote = {
            ...this.currentNote,
            name: data.title, // 使用name字段而非title
            content: data.content,
            file_ids: postData.file_ids, // 确保更新file_ids字段
            update_time: new Date().toISOString(),
          }
        }
        // 同时更新列表中的对应笔记
        this.notes = this.notes.map(note =>
          note.id === data.id
            ? { ...note, name: data.title, content: data.content, file_ids: postData.file_ids }
            : note
        )
        return response // 返回完整的response对象而不是response.data
      } catch (error) {
        throw error // 抛出错误以便上层处理
      }
    },

    // 删除笔记
    async deleteSelectedNote(id: number) {
      try {
        const response = await deleteNote(id)
        if (response.code === 0) {
          // 移除当前笔记
          if (this.currentNote && this.currentNote.id === id) {
            this.currentNote = null
          }
          // 从列表中移除笔记
          this.notes = this.notes.filter(note => note.id !== id)
          this.noteTotal = this.notes.length
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 上传附件
    async handleUploadAttachment(formData: FormData) {
      try {
        const response = await uploadAttachment(formData)
        // 如果上传成功且当前有正在编辑的笔记，自动将文件ID添加到笔记
        if (response.code === 0 && response.data && response.data.id && this.currentNote) {
          const newFileId = response.data.id
          const newAttachment = response.data
          // 先更新当前笔记的attachments数组（立即在UI上显示）
          if (!this.currentNote.attachments) {
            this.currentNote.attachments = []
          }

          // 避免重复添加到attachments数组
          if (!this.currentNote.attachments.some(att => att.id === newFileId)) {
            this.currentNote.attachments.push(newAttachment)
          }

          // 获取当前笔记的file_ids并添加新的文件ID
          const currentFileIds = this.currentNote.file_ids || ''
          const fileIdArray = currentFileIds ? currentFileIds.split(',').filter(Boolean) : []

          // 避免重复添加到file_ids字符串
          if (!fileIdArray.includes(newFileId.toString())) {
            fileIdArray.push(newFileId.toString())
            const updatedFileIds = fileIdArray.join(',')
            // 调用API更新笔记的file_ids字段
            const updateResponse = await this.updateExistingNote({
              id: this.currentNote.id,
              title: this.currentNote.name, // 使用name作为title
              content: this.currentNote.content,
              file_ids: updatedFileIds,
            })
          }
        }

        return response
      } catch (error) {
        throw error
      }
    },

    // 移除附件
    async removeNoteAttachment(noteId: number, attachmentId: number) {
      try {
        const response = await removeAttachment({ noteId, attachmentId })
        if (response.code === 0 && this.currentNote && this.currentNote.id === noteId) {
          // 从当前笔记中移除附件
          this.currentNote.attachments = this.currentNote.attachments.filter(
            attachment => attachment.id !== attachmentId
          )
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 分享笔记（适配article_access表的结构）
    async shareCurrentNote(noteId: number, config: ShareConfig) {
      try {
        const response = await shareNote({ id: noteId, ...config })
        if (response.code === 0 && this.currentNote && this.currentNote.id === noteId) {
          // 更新当前笔记的分享状态（使用status字段替代is_shared）
          this.currentNote.status = 1 // 1表示已分享
          // 模拟更新共享用户和部门（实际应从API响应获取）
          if (config.user_ids) {
            this.currentNote.shared_users = []
            // 从可选用户列表中查找共享用户
            const userIds = config.user_ids.split(',').map(id => parseInt(id))
            this.currentNote.shared_users = this.shareableUsers.filter(user =>
              userIds.includes(user.id)
            )
          }
          if (config.department_ids) {
            this.currentNote.shared_departments = []
            // 从可选部门列表中查找共享部门
            const deptIds = config.department_ids.split(',').map(id => parseInt(id))
            this.currentNote.shared_departments = this.shareableDepartments.filter(dept =>
              deptIds.includes(dept.id)
            )
          }
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 取消分享笔记（适配article_access表的结构）
    async unshareCurrentNote(noteId: number) {
      try {
        const response = await unshareNote(noteId.toString())
        if (response.code === 0 && this.currentNote && this.currentNote.id === noteId) {
          // 更新当前笔记的分享状态（使用status字段替代is_shared）
          this.currentNote.status = 0 // 0表示未分享
          this.currentNote.shared_users = []
          this.currentNote.shared_departments = []
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 获取可分享用户列表
    async fetchShareableUsers() {
      try {
        const response = await getShareableUsers()
        if (response.code === 0) {
          this.shareableUsers = response.data
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 获取可分享部门列表
    async fetchShareableDepartments() {
      try {
        const response = await getShareableDepartments()
        if (response.code === 0) {
          this.shareableDepartments = response.data
        }
        return response
      } catch (error) {
        throw error
      }
    },

    // 清空当前笔记
    clearCurrentNote() {
      this.currentNote = null
    },

    // 重置状态
    resetState() {
      this.notes = []
      this.noteTotal = 0
      this.currentNote = null
      this.loading = false
      // 保留分享列表数据，避免频繁请求
    },
  },
})
